import Taro from '@tarojs/taro';
import { baseUrl, noConsole } from '../config';

const tips = {
    1: '抱歉，服务器忙，请稍后再试',
}

type Methods = "OPTIONS" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT" | undefined
type HttpRequestParam = {
    url: string,
    data?: any,
    method?: Methods,
    header?: any,
}

class HTTP {

    /**
     * http 请求方法
     * @param param 
     */
    request(param: HttpRequestParam) {
        return this._request(param.url, param.data, param.header, param.method)
    }

    _request(url, data = {}, addHeader, method: Methods = 'GET') {
        // 请求头
        const header = {
            'content-type': 'application/json',
        }
        if (addHeader) {
            Object.assign(header, addHeader)
        }

        return Taro.request({
            url: `${baseUrl}${url}`,
            method,
            data: data,
            header,
        }).then(res => {
            const code = res.statusCode.toString()
            // console.log('success, res = ', res)
            if (code.startsWith('2')) {
                // resolve(res.data)
            } else {
                // reject()
                const { code, msg } = res.data
                if (code && msg) {
                    this._show_error_msg(code, msg)
                } else {
                    this._show_error()
                }
            }
            return res.data
        }).catch(error => {
            if (!noConsole) {
                console.error('http 请求异常, error = ', error)
            }
            this._show_error(1)
        })
    }

    /**
     * 显示服务器返回的错误信息
     * @param {*} error_code 
     * @param {String} msg 返回的消息
     */
    _show_error_msg(error_code, msg) {
        if (error_code !== 0) {
            setTimeout(() => {
                Taro.showToast({
                    title: msg,
                    icon: 'none',
                    duration: 3000
                })
            }, 0)
        }
    }

    _show_error(error_code?) {
        if (!error_code) {
            error_code = 1
        }
        const tip = tips[error_code]

        setTimeout(() => {
            Taro.showToast({
                title: tip ? tip : tips[1],
                icon: 'none',
                duration: 3000
            })
        }, 0)

    }
}

export { HTTP }